package com.jamal2362.apktool.util.search;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.List;

public class SearchHistory {
	private final String preferenceName = "search_history_";
	private final int maxLength = 30;
	private SharedPreferences preferences;
	private SharedPreferences.Editor editor;

	public SearchHistory(Context ctx) {
		preferences = ctx.getSharedPreferences(preferenceName + "global", Context.MODE_PRIVATE);
		editor = preferences.edit();
	}

	public SearchHistory(Context ctx, String tag) {
		preferences = ctx.getSharedPreferences(preferenceName + tag, Context.MODE_PRIVATE);
		editor = preferences.edit();
	}

	public List<String> getHistory() {
		List<String> history = new ArrayList<String>();
		for (int i = 0; i < maxLength; i++) {
			String item = preferences.getString("item_" + i, null);
			if (item != null) {
				history.add(item);
			}
		}
		return history;
	}
	
	public void putHistory(String text) {
		List<String> history = getHistory();
		int size = history.size();
		if (history.contains(text)) {
			boolean find = false;
			for (int i = 0; i < size - 1; i++) {
				if (history.get(i).equals(text)) {
					find = true;
				}
				if (find) {
					editor.putString("item_" + i, history.get(i + 1));
				}
			}
			editor.putString("item_" + (size - 1), text);
			editor.commit();
			return;
		}
		if (size < maxLength) {
			editor.putString("item_" + size, text);
			editor.commit();
			return;
		}
		editor.putString("item_" + (maxLength - 1), text);
		editor.commit();
		for (int i = 0; i < maxLength - 1; i++) {
			editor.putString("item_" + i, history.get(i + 1));
			editor.commit();
		}
	}
	
	public void clear() {
		editor.clear();
		editor.commit();
	}
}
